package cn.wolfcode.shop.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;

import cn.wolfcode.shop.domain.UserLogin;
import cn.wolfcode.shop.message.CreateOrderProducer;
import cn.wolfcode.shop.service.IOrderInfoService;
import cn.wolfcode.shop.vo.JSONResult;
import cn.wolfcode.shop.vo.OrderStatusChangeVo;
import cn.wolfcode.shop.vo.OrderVo;

@RestController
@RequestMapping("/api/orders")
public class OrderController {

	@Reference
	private IOrderInfoService orderInfoService;
	@Autowired
	private CreateOrderProducer createOrderProducer;

	/**
	 * 创建订单
	 * 资源:/api/orders
	 * 动作:POST
	 * @param userLogin
	 * @param orderVo
	 * @return
	 */
	@PostMapping
	public JSONResult createOrder(UserLogin userLogin, @RequestBody OrderVo orderVo) {
		orderVo.setUserLogin(userLogin);
		//		orderInfoService.createOrder(orderVo);
		// 发送一个生成订单的消息(mobile是消息生产者,order-server是消息消费者)
		//		createOrderProducer.sendMessage("创建订单queue");
		//		createOrderProducer.sendMessageByTopic("创建订单topic");
		createOrderProducer.sendMessage(JSON.toJSONString(orderVo));
		return new JSONResult();
	}

	/**
	 * 修改订单状态
	 * 路径:/api/orders/{orderId}
	 * 
	 * 选择:PATCH只需要提交部分字段
	 * 方法:PUT是需要提交一个完整的对象
	 * 需要用户登录后才能操作,参数解析器判断如果没有登录会抛出异常
	 * @return
	 */
	@PatchMapping("/{orderId}")
	public JSONResult changeOrderStatus(@PathVariable Long orderId, OrderStatusChangeVo vo, UserLogin userLogin) {
		vo.setOrderId(orderId);
		vo.setPlace("前台");
		vo.setUserName(userLogin.getUserName());
		orderInfoService.changeOrderStatus(vo);
		return new JSONResult();
	}

}
